# -*- ruby -*-

require 'ostruct'
require 'erb'

GEN_FILES = %w[ index.html rjack.png rjack.svg ]
PUB_FILES = %w[ jack_of_ruby.png style.css ] + GEN_FILES

task :default => GEN_FILES

task :clean do
  rm_f [ 'index.html', 'rjack.png', 'rjack.svg' ]
end

task :publish => PUB_FILES do
  includes = PUB_FILES.map { |f| "--include #{f}" }.join( ' ' )
  sh( "aws s3 sync --acl public-read --exclude '*' #{includes} " +
      ". s3://rjack.gravitext.com/" )
end

file 'rjack.svg' => [ 'rjack.dot' ] do
  sh "ccomps -x rjack.dot | dot | gvpack -n | neato -n2 -Tsvg > rjack.svg"
end

file 'rjack.png' => [ 'rjack.dot' ] do
  sh "ccomps -x rjack.dot | dot | gvpack -n | neato -n2 -Tpng > rjack.png"
end

def erb_generate( src, target, bindvar )
  puts "#{src} --generate--> #{target}"
  open( target, 'w' ) do |outf|
    outf.write( ERB.new( IO.read( src ) ).result( bindvar ) )
  end
end

class RowCounter
  def initialize
    @row = 0
  end

  def next
    @row += 1
    !( ( @row % 2 ) == 0 )
  end

end

file 'index.html' => [ 'index.erb', 'rjack.png' ] do
  id = `identify rjack.png`.strip
  m = id.match( /PNG (\d+)x(\d+)/ ) or raise id
  g = OpenStruct.new( :w => m[1], :h => m[2] )
  row = RowCounter.new
  erb_generate( 'index.erb', 'index.html', binding )
end
